package com.only4play.practice.message.core.domain;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.only4play.codegen.support.base.EntityOperations;
import com.only4play.codegen.support.exception.BusinessException;
import com.only4play.practice.common.enums.MessageErrorCode;
import com.only4play.practice.message.core.domain.model.MessageSendModel;
import com.only4play.practice.message.core.entity.MessageRecord;
import com.only4play.practice.message.core.entity.MessageTemplate;
import com.only4play.practice.message.core.mapper.MessageRecordMapper;
import com.only4play.practice.message.core.mapper.MessageTemplateMapper;
import com.only4play.practice.message.entitymapper.MessageRecordObjectMapper;
import com.sun.org.apache.bcel.internal.generic.NEW;
import jodd.util.StringTemplateParser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.BagUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author mengdy
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MessageRecordDomainServiceImpl implements IMessageRecordDomainService{

     private final MessageTemplateMapper messageTemplateMapper;
     private final MessageRecordMapper messageRecordMapper;

     private final ApplicationEventPublisher publisher;

  @Override
  public void sendMessage(MessageSendModel messageSendModel) {

    QueryWrapper<MessageTemplate> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("template_code",messageSendModel.getTemplateCode());
    queryWrapper.last("limit 1");
    MessageTemplate template = messageTemplateMapper.selectOne(queryWrapper);
    if(!ObjectUtil.isNotNull(template)){
      throw new BusinessException(MessageErrorCode.TEMPLATE_NOT_FIND);
    }
    // 模板内容替换
    String content = StringTemplateParser
        .ofMap(messageSendModel.getParams())
        .apply(template.getTemplate());
    EntityOperations
        .doCreate(messageRecordMapper)
        .create(() -> {
          MessageRecord messageRecord = new MessageRecord();
          BeanUtil.copyProperties(messageSendModel,messageRecord);
            Map<String, Object> params = messageSendModel.getParams();
            // 将params转化json格式
            messageRecord.setParams(JSONObject.toJSONString(params));
            return messageRecord;
        })
        .update(e -> e.init(content,publisher))
        .execute();
  }
}
